﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using CKEditor.NET;
using Telerik.Web.UI;
using System.Linq;
using Web_Oto.Business;
using Web_Oto.Common;
using Web_Oto.Data;
using Web_Oto.Data.Dto;

namespace Administration
{
    public partial class Product : Page
    {
        private ProductBus _business;
        private CategoryBus _categoryBus;
        private string _imagePath = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _business = new ProductBus();
            _categoryBus = new CategoryBus();
            _imagePath = ConfigurationManager.AppSettings["productPath"];

            if (!Page.IsPostBack)
            {
                hdfActiveSearch.Value = "0";

                var categories = _categoryBus.GetChildrenCategoryDtos();
                categories.Insert(0, new Web_Oto.Data.Category { Id = 0, Name = " --- CHỌN LOẠI XE --- " });
                rcbchildrenCategory.DataSource = categories;
                rcbchildrenCategory.DataValueField = "Id";
                rcbchildrenCategory.DataTextField = "Name";
                rcbchildrenCategory.DataBind();
            }
        }

        protected void grid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            var categoryId = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"].ToString();
            int id;
            int.TryParse(categoryId, out id);

            var fileName = _business.GetFilePathById(id);
            CommonHelper.DeleteFile(_imagePath, fileName);

            var result = _business.Delete(id);
            if (result > 0)
            {
                msgBox.InnerHtml = "<p><strong>Xóa thành công</strong></p>";
                msgBox.Attributes["class"] = "msg msg-ok";
            }
            else
            {
                msgBox.InnerHtml = "<p><strong>Xóa không thành công</strong></p>";
                msgBox.Attributes["class"] = "msg msg-error";
            }
        }

        protected void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            if (hdfActiveSearch.Value == "1")
            {
                var strCategoryId = rcbchildrenCategory.SelectedValue;
                int categoryId;
                int.TryParse(strCategoryId, out categoryId);
                grid.DataSource = _business.GetProductDtos(txtName.Text, categoryId);
            }
            else
                grid.DataSource = _business.GetProductDtos();
        }

        protected void grid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
            {
                var edititem = (GridEditableItem) e.Item;
                var values = new Hashtable();
                edititem.ExtractValues(values);

                var id = 0;
                try
                {
                    if (edititem.GetDataKeyValue("Id") != null)
                        id = (int) edititem.GetDataKeyValue("Id");
                }
                catch (Exception)
                {
                }

                //Load data for drop list box.
                var ddlCategory = ((RadComboBox) edititem.FindControl("ddlCategory"));
                var categories = _categoryBus.GetChildrenCategoryDtos();
                categories.Insert(0, new Web_Oto.Data.Category {Id = 0, Name = " --- CHỌN LOẠI XE --- "});
                ddlCategory.DataSource = categories;
                ddlCategory.DataValueField = "Id";
                ddlCategory.DataTextField = "Name";
                ddlCategory.DataBind();

                var categoryId = ((HiddenField) edititem.FindControl("categoryId")).Value;
                ddlCategory.SelectedValue = string.IsNullOrEmpty(categoryId) ? "0" : categoryId;

                var productDtos = (List<ProductDto>) grid.DataSource;
                //Relative products of selected product.
                if (id > 0)
                {
                    var relativePoductDtos = _business.GetRelativeProductDto(id);
                    var relativeProducts = ((RadListBox) edititem.FindControl("ListBoxFunctionUpdate"));
                    relativeProducts.DataSource = relativePoductDtos;
                    relativeProducts.DataTextField = "Name";
                    relativeProducts.DataValueField = "Id";
                    relativeProducts.DataBind();

                    productDtos =
                        productDtos.Where(p => !relativePoductDtos.Any(p1 => p1.Id == p.Id) && p.Id != id).ToList();
                }

                //All products to related products.
                var products = ((RadListBox) edititem.FindControl("ListBoxFunctions"));
                products.DataSource = productDtos;
                products.DataTextField = "Name";
                products.DataValueField = "Id";
                products.DataBind();
            }
        }

        protected void grid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            var gdItem = (e.Item as GridEditFormItem);
            var editableItem = ((GridEditableItem) e.Item);
            var values = new Hashtable();
            editableItem.ExtractValues(values);          
            
            var productDto = new ProductDto
                                 {
                                     Id = (int) editableItem.GetDataKeyValue("Id"),                                     
                                     ShowInNews = (bool) values["ShowInNews"],
                                     ShowInHomePage = (bool) values["ShowInHomePage"],
                                     ShowInConsultServices = (bool) values["ShowInConsultServices"],
                                     ShowInPayment = (bool) values["ShowInPayment"]
                                 };

            if (gdItem != null)
            {
                var ddlCategory = gdItem.FindControl("ddlCategory") as RadComboBox;
                var editDescription = gdItem.FindControl("editDescription") as CKEditorControl;
                var cbRelatedProducts = gdItem.FindControl("ListBoxFunctionUpdate") as RadListBox;
                var txtSEO_Title = gdItem.FindControl("txtSEO_Title") as RadTextBox;
                var txtSEO_Keyword = gdItem.FindControl("txtSEO_Keyword") as RadTextBox;
                var txtSEO_Description = gdItem.FindControl("txtSEO_Description") as RadTextBox;
                var txtName = gdItem.FindControl("txtName") as RadTextBox;
                var txtPrice = gdItem.FindControl("txtPrice") as RadTextBox;
                var txtHotline = gdItem.FindControl("txtHotline") as RadTextBox;
                var txtTitleOfImage = gdItem.FindControl("txtTitleOfImage") as RadTextBox;

                var uploader = gdItem.FindControl("uploadAvatar") as RadUpload;
                var hdfImage = ((HiddenField) gdItem.FindControl("hdfImage"));

                if (ddlCategory != null && editDescription != null && cbRelatedProducts != null
                    && uploader != null && hdfImage != null && txtSEO_Title != null &&
                    txtSEO_Keyword != null && txtSEO_Description != null &&
                    txtName != null && txtPrice != null && txtHotline != null &&
                    txtTitleOfImage != null)
                {
                    editDescription.Language = "vi";
                    var fileBrowser = new CKFinder.FileBrowser { BasePath = "/ckfinder/" };
                    fileBrowser.SetupCKEditor(editDescription);

                    if (uploader.UploadedFiles.Count > 0)
                    {
                        var oldPathImage = hdfImage.Value;
                        var avatar = uploader.UploadedFiles[0].FileName;
                        var filePath = CommonHelper.GetFilePath(_imagePath, ref avatar, oldPathImage);
                        uploader.UploadedFiles[0].SaveAs(Server.MapPath(filePath));
                        //productDto.Image = filePath;
                        productDto.Image = avatar;
                    }

                    var strCategoryId = ddlCategory.SelectedValue;
                    int categoryId;
                    var isUpdateRelation = false;
                    int.TryParse(strCategoryId, out categoryId);

                    productDto.SEO_Title = txtSEO_Title.Text;
                    productDto.SEO_Keyword = txtSEO_Keyword.Text;
                    productDto.SEO_Description = txtSEO_Description.Text;
                    productDto.CategoryId = categoryId;
                    productDto.Description = editDescription.Text;
                    productDto.RelativeProducts = new List<RelativeProduct>();
                    productDto.Name = txtName.Text;
                    productDto.Price = txtPrice.Text;
                    productDto.Hotline = txtHotline.Text;
                    productDto.TitleOfImage = txtTitleOfImage.Text;

                    if (!CheckValidData(productDto.Name, categoryId))
                        return;

                    if (cbRelatedProducts.ClientChanges.Count > 0)
                    {
                        foreach (var item in cbRelatedProducts.Items)
                        {
                            var relatedProduct = new RelativeProduct
                                                     {ProductId = Convert.ToInt32(((RadListBoxItem) item).Value)};
                            productDto.RelativeProducts.Add(relatedProduct);
                        }
                        isUpdateRelation = true;
                    }

                    var result = _business.Update(productDto, isUpdateRelation);
                    if (result > 0)
                    {
                        msgBox.InnerHtml = "<p><strong>Cập nhật thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-ok";
                    }
                    else
                    {
                        msgBox.InnerHtml = "<p><strong>Cập nhật không thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-error";
                    }
                }
            }
        }

        protected void grid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            var gdItem = (e.Item as GridEditFormItem);
            var editableItem = ((GridEditableItem) e.Item);
            var values = new Hashtable();
            editableItem.ExtractValues(values);           

            var productDto = new ProductDto
                                 {                                    
                                     ShowInNews = (bool) values["ShowInNews"],
                                     ShowInHomePage = (bool) values["ShowInHomePage"],
                                     ShowInConsultServices = (bool) values["ShowInConsultServices"],
                                     ShowInPayment = (bool) values["ShowInPayment"]
                                 };

            if (gdItem != null)
            {
                var ddlCategory = gdItem.FindControl("ddlCategory") as RadComboBox;
                var editDescription = gdItem.FindControl("editDescription") as CKEditorControl;
                var cbRelatedProducts = gdItem.FindControl("ListBoxFunctionUpdate") as RadListBox;
                var uploader = gdItem.FindControl("uploadAvatar") as RadUpload;
                var txtSEO_Title = gdItem.FindControl("txtSEO_Title") as RadTextBox;
                var txtSEO_Keyword = gdItem.FindControl("txtSEO_Keyword") as RadTextBox;
                var txtSEO_Description = gdItem.FindControl("txtSEO_Description") as RadTextBox;
                var txtName = gdItem.FindControl("txtName") as RadTextBox;
                var txtPrice = gdItem.FindControl("txtPrice") as RadTextBox;
                var txtHotline = gdItem.FindControl("txtHotline") as RadTextBox;
                var txtTitleOfImage = gdItem.FindControl("txtTitleOfImage") as RadTextBox;

                if (ddlCategory != null && editDescription != null
                    && cbRelatedProducts != null && uploader != null && txtSEO_Title != null &&
                    txtSEO_Keyword != null && txtSEO_Description != null &&
                    txtName != null && txtPrice != null && txtHotline != null &&
                    txtTitleOfImage != null)
                {
                    editDescription.Language = "vi";
                    var fileBrowser = new CKFinder.FileBrowser { BasePath = "/ckfinder/" };
                    fileBrowser.SetupCKEditor(editDescription);

                    if (uploader.UploadedFiles.Count > 0)
                    {
                        var avatar = uploader.UploadedFiles[0].FileName;
                        var filePath = CommonHelper.GetFilePath(_imagePath, ref avatar);
                        uploader.UploadedFiles[0].SaveAs(Server.MapPath(filePath));
                        //productDto.Image = filePath;
                        productDto.Image = avatar;
                    }

                    var strCategoryId = ddlCategory.SelectedValue;
                    int categoryId;
                    int.TryParse(strCategoryId, out categoryId);                    

                    productDto.SEO_Title = txtSEO_Title.Text;
                    productDto.SEO_Keyword = txtSEO_Keyword.Text;
                    productDto.SEO_Description = txtSEO_Description.Text;
                    productDto.CategoryId = categoryId;
                    productDto.Description = editDescription.Text;
                    productDto.RelativeProducts = new List<RelativeProduct>();
                    productDto.Name = txtName.Text;
                    productDto.Price = txtPrice.Text;
                    productDto.Hotline = txtHotline.Text;
                    productDto.TitleOfImage = txtTitleOfImage.Text;

                    if (!CheckValidData(productDto.Name, categoryId))
                        return;

                    foreach (var item in cbRelatedProducts.Items)
                    {
                        var relatedProduct = new RelativeProduct
                                                 {ProductId = Convert.ToInt32(((RadListBoxItem) item).Value)};
                        productDto.RelativeProducts.Add(relatedProduct);
                    }

                    var result = _business.Insert(productDto);
                    if (result > 0)
                    {
                        msgBox.InnerHtml = "<p><strong>Thêm mới thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-ok";
                    }
                    else
                    {
                        msgBox.InnerHtml = "<p><strong>Thêm mới không thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-error";
                    }
                }
            }
        }

        private bool CheckValidData(string name, int categoryId)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                msgBox.InnerHtml = "<p><strong>Vui lòng nhập tên cho sản phẩm</strong></p>";
                msgBox.Attributes["class"] = "msg msg-error";

                return false;
            }

            if (categoryId == 0)
            {
                msgBox.InnerHtml = "<p><strong>Vui lòng chọn loại xe</strong></p>";
                msgBox.Attributes["class"] = "msg msg-error";

                return false;
            }

            return true;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //Keep show status of box search.
            hdfActiveSearch.Value = "1";

            //Search product by name and category.
            var strCategoryId = rcbchildrenCategory.SelectedValue;
            int categoryId;
            int.TryParse(strCategoryId, out categoryId);
            grid.DataSource = _business.GetProductDtos(txtName.Text, categoryId);
            grid.DataBind();
        }
    }
}